import { defineComponent, reactive, Ref, ref, toRefs } from 'vue'
import {
  NForm,
  NFormItem,
  NModal,
  NCheckbox,
  NCheckboxGroup,
  NSelect,
  FormRules,
  SelectOption
} from 'naive-ui'
import { Response } from '@/service/modules/common/types'
import { modProPrivilegeReq } from '@/service/modules/data-manage'
import { searchProByNameReq } from '@/service/modules/project'

const GrantProPrivilegeModal = defineComponent({
  name: 'GrantProPrivilegeModal',
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    tableId: {
      type: Number,
      required: true
    }
  },
  emits: ['modalShowChange', 'refreshList'],
  setup() {
    const state = reactive({
      form: {
        proId: null
      },
      positiveButtonDisabled: ref(false),
      rules: {
        proId: {
          trigger: ['input', 'blur'],
          validator() {
            if (!state.form.proId) {
              return new Error(window.$t('project.selectProjectTips'))
            }
          }
        }
      } as FormRules
    })
    const privilegesValues: Ref<string[]> = ref([])
    const loadingRef = ref(false)
    const optionsRef = ref<SelectOption[]>([])
    return {
      ...toRefs(state),
      privilegesValues,
      loadingRef,
      optionsRef
    }
  },
  methods: {
    async onPositiveClick() {
      //提交添加用户权限请求
      this.positiveButtonDisabled = true
      const res: Response<any> = await modProPrivilegeReq({
        proId: this.form.proId,
        tableId: this.tableId,
        privileges: this.privilegesValues + ''
      }).catch(() => {
        this.positiveButtonDisabled = false
      })
      if (res.resp_code === 0) {
        this.initData()
        this.$emit('modalShowChange', false)
        this.$emit('refreshList')
        this.positiveButtonDisabled = false
      } else {
        this.positiveButtonDisabled = false
      }
    },
    onNegativeClick() {
      this.initData()
      this.$emit('modalShowChange', false)
    },
    initData() {
      this.form.proId = null
      this.privilegesValues = []
    },
    async handleSearch(query: string) {
      if (!query.length) {
        this.optionsRef = []
        return
      }
      this.loadingRef = true
      const res = await searchProByNameReq({ name: query }).catch(() => {
        this.loadingRef = false
      })
      if (res.resp_code === 0) {
        this.optionsRef = res.data
      }
      this.loadingRef = false
    }
  },
  render() {
    return (
      <NModal
        show={this.showModal}
        mask-closable={false}
        style='width: 400px'
        title={window.$t('dataManage.modPrivilege')}
        bordered={false}
        size='huge'
        preset='dialog'
        positive-text={window.$t('dialog.positiveText')}
        negative-text={window.$t('dialog.negativeText')}
        onPositiveClick={this.onPositiveClick}
        onNegativeClick={this.onNegativeClick}
        onClose={this.onNegativeClick}
        positiveButtonProps={{
          disabled: this.positiveButtonDisabled || !this.form.proId
        }}
      >
        <NForm
          label-placement='top'
          require-mark-placement='right-hanging'
          label-width='auto'
          rules={this.rules}
        >
          <NFormItem path='privileges'>
            <NCheckboxGroup v-model:value={this.privilegesValues}>
              <NCheckbox value='SELECT' label='SELECT' />
              <NCheckbox value='INSERT' label='INSERT' />
              <NCheckbox value='UPDATE' label='UPDATE' />
              <NCheckbox value='DELETE' label='DELETE' />
            </NCheckboxGroup>
          </NFormItem>
          <NFormItem path='proId'>
            <NSelect
              v-model:value={this.form.proId}
              filterable
              placeholder={window.$t('project.searchProject')}
              options={this.optionsRef}
              label-field='name'
              value-field='id'
              loading={this.loadingRef}
              clearable
              remote
              clear-filter-after-select
              onSearch={this.handleSearch}
            ></NSelect>
          </NFormItem>
        </NForm>
      </NModal>
    )
  }
})

export default GrantProPrivilegeModal
